package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
//import com.sun.org.apache.xpath.internal.operations.String;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.UUID;

@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<User> login(String username, String password) {
        int rc = userMapper.checkUserName(username);
        if (rc==0){
            return ServerResponse.createByErrorMessage("当前用户不存在");
        }

        // todo 密码登录md5
        String md5paddword = MD5Util.MD5EncodeUtf8(password);

        User user = userMapper.selectLogin(username,md5paddword);
        if (user==null){
            return ServerResponse.createByErrorMessage("密码错误");
        }
        user.setPassword(StringUtils.EMPTY);

        return ServerResponse.createBySuccess("登录成功",user);
    }

    public ServerResponse<String> register(User user){
        ServerResponse<String> serverUser = this.checkValid(user.getUsername(),Const.USER_NAME);
        if (!serverUser.isSuccess()){
            return serverUser;
        }
        ServerResponse<String> serverEmail = this.checkValid(user.getEmail(),Const.EMAIL);
        if (!serverEmail.isSuccess()){
            return serverEmail;
        }

        user.setRole(Const.Role.ROLE_CUSTOMER);
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int rc = userMapper.insert(user);
        if (rc==0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    public ServerResponse<String> checkValid(String str,String type){
        if (StringUtils.isNotBlank(type)){
            if (Const.USER_NAME.equals(type)){
                int rc = userMapper.checkUserName(str);
                if (rc>0){
                    return ServerResponse.createByErrorMessage("当前用户已经存在");
                }
            }
            if (Const.EMAIL.equals(type)){
                int em = userMapper.checkEmail(str);
                if (em>0){
                    return ServerResponse.createByErrorMessage("当前email已经存在");
                }
            }
        }else {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    public ServerResponse<String> getQuestion(String username){
        ServerResponse<String> serverResponse = this.checkValid(username,Const.USER_NAME);
        if (serverResponse.isSuccess()){
            return ServerResponse.createByErrorMessage("当前用户不存在");
        }
        String question = userMapper.getQuestion(username);
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(question)){
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("找回密码的问题是空的");
    }

    public ServerResponse<String> getproblem(String username,String question,String answer){
        int count = userMapper.getproblem(username,question,answer);
        if (count>0){
            String forGetToken = UUID.randomUUID().toString();
            TokenCache.setKey(Const.TOKEN+username,forGetToken);
            return ServerResponse.createBySuccess(forGetToken);
        }
        return ServerResponse.createByErrorMessage("问题的答案错误");
    }

    public ServerResponse<String> forGetPassword(String username,String password,String forGetToken){
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(forGetToken)){
            return ServerResponse.createByErrorMessage("参数错误：token传递");
        }
        ServerResponse<String> serverResponse = this.checkValid(username,Const.USER_NAME);
        if (serverResponse.isSuccess()){
            return ServerResponse.createByErrorMessage("当前用户不存在");
        }
        String token = TokenCache.getKey(Const.TOKEN+username);
        if (StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("token无效");
        }
        if (StringUtils.equals(forGetToken,token)){
            String md5pas = MD5Util.MD5EncodeUtf8(password);
            int s = userMapper.forGetPassword(username,md5pas);
            if (s>0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        }else {
            return ServerResponse.createByErrorMessage("token错误请重新获取密码");
        }
        return ServerResponse.createByErrorMessage("密码修改失败");
    }

    public ServerResponse<String> resetPassword(String password,String newpassword,User user){
        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(password),user.getId());
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }

        user.setPassword(MD5Util.MD5EncodeUtf8(newpassword));
        int updataUser = userMapper.updateByPrimaryKeySelective(user);
        if (updataUser>0){
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createByErrorMessage("密码更新错误");
    }

    public ServerResponse<User> updateInformation(User user){
        int count = userMapper.checkEmailUserId(user.getEmail(),user.getId());
        if (count>0){
            return ServerResponse.createByErrorMessage("当前email已经被注册了");
        }
        User users = new User();
        users.setEmail(user.getEmail());
        users.setAnswer(user.getAnswer());

        int countUser = userMapper.updateByPrimaryKeySelective(users);
        if (countUser>0){
            return ServerResponse.createBySuccess("信息更新成功",users);
        }else {
            return ServerResponse.createByErrorMessage("用户信息更新失败");
        }

    }

    public ServerResponse<User> getInformation(User user){
        User users = userMapper.selectByPrimaryKey(user.getId());
        if (users==null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        users.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(users);
    }

    // 判断当前权限
    public ServerResponse checkAdminRole(User user){
        if (user!=null&&user.getRole()==Const.Role.ROLE_ADMIN){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }
}
